/*
 * Queue.java
 * This file is part of the <a href="http://code.google.com/p/pux">PUX Framework</a>
 *
 * Copyright 2008 by <a href="mailto:jfendler@polytechnic.edu.na">Jens Fendler</a>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package de.teamskill.pux.library.util;

import java.util.List;
import java.util.Vector;

import de.teamskill.pux.engine.AbstractNode;
import de.teamskill.pux.engine.OutputPort;
import de.teamskill.pux.engine.Port;

/**
 * Queue - pass through every incoming object as soon as possible. If the target
 * node's input port is occupied, incoming objects are stored and pushed forward
 * when the port becomes free again.
 * 
 * @author <a href="mailto:jfendler@polytechnic.edu.na">Jens Fendler</a>
 * 
 */
public class Queue extends AbstractNode {

	/**
	 * IN_DATA
	 */
	private static final String IN_DATA = "DATA";

	/**
	 * OUT_DATA
	 */
	private static final String OUT_DATA = "DATA";

	/**
	 * QUERY_DELEY - time in ms to wait between two queries to the remote input
	 * port regarding a free input buffer
	 */
	protected static final long QUERY_DELEY = 50;

	/**
	 * queue
	 */
	private List<Object> queue = new Vector<Object>();

	/**
	 * queueThreadRunning
	 */
	private boolean queueThreadRunning = false;

	/**
	 * Queue Constructor
	 * 
	 */
	public Queue() {
		this("QUEUE" + nr++, false);
	}

	/**
	 * Queue Constructor
	 * 
	 * @param nodeName
	 * @param continuous
	 */
	public Queue(String nodeName, boolean continuous) {
		super(nodeName, continuous);
	}

	/**
	 * @see de.teamskill.pux.engine.AbstractNode#compute()
	 */
	public void compute() {
		Object data = getInputPort().fetchData();
		if (getOutputPort().getRemotePort().hasDataElement() || queueInUse()) {
			// remote port is busy. start new thread waiting to push the object
			LOG_NODE.fine("Enqueing object. Hash= " + data.hashCode());
			queue.add(data);
			if (!queueThreadRunning) {
				startQueueThread();
			}
		} else {
			// push the object through immediately (without a new thread)
			getOutputPort().pushData(data);
		}
	}

	/**
	 * startQueueThread
	 * 
	 */
	private synchronized void startQueueThread() {
		new Thread(new Runnable() {
			public void run() {
				OutputPort localPort = getOutputPort();
				Port remotePort = localPort.getRemotePort();
				queueThreadRunning = true;
				while (queueInUse()) {
					boolean interrupted = false;
					while (remotePort.hasDataElement()) {
						try {
							Thread.sleep(QUERY_DELEY);
						} catch (InterruptedException e) {
							interrupted = true;
							LOG_NODE.warning(getNodeName()
									+ ": Queue Thread interrupted while waiting for remote node: "
									+ e.getLocalizedMessage());
							break;
						}
					}
					if (!interrupted) {
						synchronized (queue) {
							Object next = queue.remove(0);
							localPort.pushData(next);
						}
					}
				}
				queueThreadRunning = false;
			}
		}).start();
	}

	/**
	 * queueInUse
	 * 
	 * @return
	 */
	private boolean queueInUse() {
		synchronized (queue) {
			return queue.size() > 0;
		}
	}

	/**
	 * @see de.teamskill.pux.engine.AbstractNode#createPorts()
	 */
	protected void createPorts() {
		addInputPort(IN_DATA, null, true);
		addOutputPort(OUT_DATA, null);
	}

}
